package com.zero.common.threadpool;

import com.zero.common.core.utils.ThreadUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.util.TimerTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 异步任务管理器
 * 
 * @author ruoyi
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class AsyncManager {
    /**
     * 异步操作任务调度线程池
     */
    private final ScheduledExecutorService scheduledExecutorService;

    /**
     * 执行任务
     *
     * @param task 任务
     */
    public void execute(TimerTask task) {
        scheduledExecutorService.schedule(task, 10, TimeUnit.MILLISECONDS);
    }

    /**
     * 停止任务线程池
     */
    @PreDestroy
    public void shutdown() {
        try {
            log.info("【关闭后台任务任务线程池】");
            ThreadUtil.shutdownAndAwaitTermination(scheduledExecutorService);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}
